package middleware

import (
	"bytes"
	"team-evaluate/global"
	"time"

	"github.com/gin-gonic/gin"
)

type AccessLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

// 实现了双写
func (w AccessLogWriter) Write(p []byte) (int, error) {
	if n, err := w.body.Write(p); err != nil {
		return n, err
	}
	return w.ResponseWriter.Write(p)
}

// AccessLog 记录访问日志
func AccessLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		bodyWriter := &AccessLogWriter{
			body:           bytes.NewBufferString(""),
			ResponseWriter: c.Writer,
		}
		c.Writer = bodyWriter
		beginTime := time.Now().Unix()

		c.Next()

		endTime := time.Now().Unix()
		requestParams, ok := c.Get("request_params")
		if !ok {
			requestParams = "nil"
		}
		global.Logger.Infof("access log: method: %s, status_code: %d, begin_time: %d, end_time: %d, request: %s, response: %s",
			c.Request.Method,
			bodyWriter.Status(),
			beginTime,
			endTime,
			requestParams,
			bodyWriter.body.String(),
		)
	}
}
